import React, { useEffect, useState, useMemo } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect, useIntl, history } from 'umi';

import type { Dispatch } from 'umi';
import type { StateType, DataType } from './model';
import { Form, Select, Radio, Button, Input, Divider, RadioChangeEvent, message, Modal } from 'antd';
import { UploadFile, RcFile, UploadChangeParam } from 'antd/lib/upload/interface';
import { InboxOutlined, ExclamationCircleOutlined } from '@ant-design/icons';

import { SpeNameReg } from '@/utils/reg';
import { bizCodeMessage } from '@/utils/errCode';
import { MODULE_NAME } from '@/utils/const';

import Uppy from '@uppy/core';
import { Dashboard } from '@uppy/react';
import '@uppy/dashboard/dist/style.css';
import Chinese from '@uppy/locales/lib/zh_CN';
import Tus from '@uppy/tus';

import { addUnstructuredDataSet, getFileInfo } from './service';
import { values } from 'lodash';

const { Option } = Select;

const formItemLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 10 },
};

const tailLayout = {
  wrapperCol: { offset: 6, span: 6 },
};

interface AddProps {
  dataSet: {
    dataTypes: DataType[];
  };
  dispatch: Dispatch;
}

const AddDataSet: React.FC<AddProps> = props => {
  const { formatMessage: f } = useIntl();
  const {
    dispatch,
    dataSet: {
      dataTypes,
    },
  } = props;

  const [dsWithAnnot, setDsWithAnnot] = useState<boolean>(false);
  const [dataType, setDataType] = useState<string>('cv'); // 当前数据类型
  const [dataTask, setDataTask] = useState<string>(''); // 当前数据任务
  const [dataTasks, setDataTasks] = useState<DataType[]>([]);
  const [annotFormats, setAnnotFormats] = useState<DataType[]>([]);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [filePath, setFilePath] = useState<string>('');
  const [fileName, setFileName] = useState<string>('');

  const [form] = Form.useForm();

  const uppy = useMemo(() => {
    const options = {
      meta: {
        location: MODULE_NAME,
        moduleName: MODULE_NAME,
      },
      restrictions: {
        maxNumberOfFiles: 1,
        allowedFileTypes: ['.zip', '.tar', '.gz'],
      },
      locale: Chinese,
    }
    return new Uppy(options).use(Tus, {
      formData: true,
      // headers: {
      //   Authorization: 'Bearer ' + window.localStorage.token,
      // },
      fieldName: 'file',
      endpoint: '/file-server/api/v1/files',
      chunkSize: 4 * 1024 * 1024, // 分片大小
    }).on('complete', async (result) => {
      console.log(result)
      const uploadURL = result?.successful[0]?.uploadURL;
      const uploadName = result?.successful[0]?.name;
      const fileId = uploadURL?.split('/').pop();
      // console.log(fileId);
      // 根据 fileId 获取文件pvc路径，然后传给后端 http://yapi.apulis.cn:8444/project/518/interface/api/20934

      const { code, data, msg } = await getFileInfo(fileId) || {};

      if (code === 0) {
        let { storagePath } = data;
        setFilePath(storagePath);
        //
        setFileName(uploadName);
      }
    }).on('file-removed', () => {
      setFilePath('');
    });
  }, []);

  useEffect(() => {
    if (!dataTypes.length) {
      dispatch({ type: 'dataSet/getDataType' });
    }

    return () => uppy.close();
  }, []);

  useEffect(() => {
    if (dataTypes.length > 0) {
      const type = dataTypes.find(t => t.value === dataType);
      if (type?.children) {
        setDataTasks(type.children);
      }
    }
  }, [dataTypes]);

  useEffect(() => {
    const type = dataTypes.find(t => t.value === dataType);
    if (type?.children) {
      setDataTasks(type.children);
    }
  }, [dataType]);

  useEffect(() => {
    const task = dataTasks.find(t => t.value === dataTask);
    if (task?.children) {
      setAnnotFormats(task?.children);
    }
  }, [dataTask]);

  const onChangeWithAnnot = (e: RadioChangeEvent) => {
    setDsWithAnnot(e.target.value);
  };

  const onChangeDataType = (e: any) => {
    setDataType(e);
    form.setFieldsValue({
      dataTask: '',
    });
  };

  const onChangeDataTask = (e: any) => {
    setDataTask(e);
    form.setFieldsValue({
      annotFormat: '',
    });
  };

  const onFinish = async (values: any) => {
    console.log('Received values of form: ', values);

    if (!filePath) {
      message.error("请先上传数据集文件！");
      return;
    }

    const { name, description, dsType, dataTask, dataType, ownerType, sourceType, withAnnot, annotFormat } = values;

    if (dsType === "unstructured") {
      try {
        const { code, data, msg } = await addUnstructuredDataSet({ name, description, ownerType, dataType, dataTask, withAnnot, annotFormat, sourceType, filePath, fileName });
        if (code === 0) {
          message.success('创建成功！');
          // 跳转到数据集仓库页面
          history.push('/dataManage/dataSet/list');
        } else {
          message.error(`创建数据集失败：${msg}`);
        }
      } catch (ex) {
        // message.error(`创建数据集失败!`);
        console.log(ex);
      }
    }
  };

  const onBack = () => {
    const inputs = form.getFieldsValue(['dataTask', 'dataType', 'description', 'name', 'uppyFile']);

    const hasInput = Object.values(inputs).some(i => !!i);

    if (hasInput) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleOutlined />,
        content: '页面已填内容将会丢失，是否继续？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          form.resetFields();
          history.push('/dataManage/dataSet/list');
        },
      });
    } else {
      form.resetFields();
      history.push('/dataManage/dataSet/list');
    }
  }

  return (
    <PageHeaderWrapper onBack={() => onBack()}>
      <Form
        name="add_dataset"
        form={form}
        {...formItemLayout}
        onFinish={onFinish}
        initialValues={{
          withAnnot: false,
          dsType: 'unstructured',
          sourceType: 'upload_from_page',
          ownerType: 'org',
          dataType: 'cv',
        }}
      >
        <Form.Item label="名称" name='name'
          rules={[{ required: true, message: '请输入数据集名称' }, SpeNameReg]}
        >
          <Input placeholder='请输入数据集名称' maxLength={101} />
        </Form.Item>
        <Form.Item label="描述" name='description'>
          <Input.TextArea showCount maxLength={2000} placeholder='请输入描述' rows={5} />
        </Form.Item>
        <Form.Item label="是否公开" name='ownerType'
          rules={[{ required: true, message: '请选择是否公开' }]}
        >
          <Radio.Group>
            <Radio value="group">否</Radio>
            <Radio value="org">是</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="dsType"
          label="数据集结构"
          rules={[{ required: true, message: '请选择数据集结构' }]}
          hidden
        >
          <Radio.Group buttonStyle="solid">
            <Radio.Button value="unstructured">非结构化</Radio.Button>
            {/* <Radio.Button value="structured">结构化</Radio.Button> */}
          </Radio.Group>
        </Form.Item>
        {/* <Form.Item
          name="fileFormat"
          label="文件格式"
          hasFeedback
          rules={[{ required: true, message: '请选择文件格式' }]}
        >
          <Select placeholder="请选择文件格式">
            <Option value="CSV">CSV</Option>
            <Option value="Parquet">Parquet</Option>
          </Select>
        </Form.Item> */}
        <Form.Item
          name="dataType"
          label="数据类型"
          hasFeedback
          rules={[{ required: true, message: '请选择数据类型' }]}
          hidden
        >
          <Select placeholder="请选择数据类型" options={dataTypes} onChange={onChangeDataType}>
          </Select>
        </Form.Item>
        <Form.Item
          name="dataTask"
          label="数据任务"
          hasFeedback
          rules={[{ required: true, message: '请选择数据任务' }]}
        >
          <Select placeholder="请选择数据任务" options={dataTasks} onChange={onChangeDataTask}>
          </Select>
        </Form.Item>
        <Form.Item label="是否包含标注信息" name='withAnnot'
          rules={[{ required: true, message: '请选择是否包含标注' }]}
        >
          <Radio.Group onChange={onChangeWithAnnot}>
            <Radio value={false}>否</Radio>
            <Radio value={true}>是</Radio>
          </Radio.Group>
        </Form.Item>
        {dsWithAnnot && (<Form.Item
          name="annotFormat"
          label="标注格式"
          hasFeedback
          rules={[{ required: true, message: '请选择标注格式' }]}
        >
          <Select placeholder="请选择标注格式" options={annotFormats}>
          </Select>
        </Form.Item>)}
        <Divider dashed />
        <Form.Item label="数据来源" name='sourceType'
          rules={[{ required: true, message: '请选择数据来源' }]}
        >
          <Radio.Group>
            <Radio value="upload_from_page">本地上传</Radio>
            {/* <Radio value="import">平台导入</Radio> */}
          </Radio.Group>
        </Form.Item>
        <Form.Item
          required
          label="上传文件"
        >
        </Form.Item>
        <Form.Item
          name='uppyFile'
          wrapperCol={{ offset: 2, span: 10 }}
        >
          <Dashboard
            width='100%'
            height='100%'
            note='Images up to 200×200px'
            uppy={uppy}
            locale={{
              strings: {
                dropPaste: `点击%{browse}或将文件拖拽到这里上传。(只支持上传.zip .tar .tar.gz)`,
                browse: '上传',
                youCanOnlyUploadFileTypes: '只支持上传格式为%{types}的文件',
                done: '重置',
              },
            }}
          // doneButtonHandler={() => {
          //   uppy.reset();
          //   setFilePath('');
          // }}
          />
        </Form.Item>
        <Form.Item {...tailLayout} >
          <Button htmlType="button" onClick={onBack} style={{ marginRight: 50 }}>
            取消
          </Button>
          <Button type="primary" htmlType="submit">
            创建
          </Button>
        </Form.Item>
      </Form>
    </PageHeaderWrapper>
  )
}

export default connect(({ dataSet }: { dataSet: StateType }) => ({
  dataSet,
}))(AddDataSet);